<?php

$userID = $m['UserID'];
$schoolID = $m['SchoolID'];
$familyID = $m['FamilyID'];
signupPrepDB();

$curView = '';
if (@$_REQUEST['view']) {
    if ($_REQUEST['view'] == 'ADMIN') {
        if (isAdmin($userID))
            $curView = 'ADMIN';
    }
    if ($_REQUEST['view'] == 'FAMILY' && $familyID)
        $curView = 'FAMILY';
    elseif ($_REQUEST['view'] == 'TEACHER')
        $curView = 'TEACHER';
} 
if (!@$_REQUEST['view']) {
    if ($familyID) $curView = 'FAMILY';
    else $curView = 'TEACHER';
}
if(!headers_sent()) header('Content-type: text/html; charset=utf-8');
?>
<html>
<head>
<link rel="stylesheet" href="jslibs/jquery-ui-1.11.2.custom/jquery-ui.min.css">
<link rel="stylesheet" type="text/css" href="users/usrtempl/style.css" />
<style>
table, th, td {
   border: 1px solid black;
   margin: 0px;
}
</style>
<script src="jslibs/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="jslibs/jquery-ui-1.11.2.custom/jquery-ui.js" type="text/javascript"></script>
<script src="jslibs/jquery.PrintArea.js" type="text/JavaScript" language="javascript"></script>
<script type="text/javascript">
var userID = <?= $userID ?>;
var schoolID = <?= $schoolID ?>;
var familyID = <?= $familyID ?>;
var curView = '<?= $curView ?>';
var madeChanges = false;
function showSchedule()
{
    console.log('showSchedule(): Entering');
    if (curView == 'TEACHER') {
        url='list_byfamily.php?action=ajax_load&school_id='+schoolID+'&all_active_sets=1&teacher_id='+encodeURIComponent(userID);
    } else {
        url='list_byfamily.php?action=ajax_load&school_id='+schoolID+'&all_active_sets=1&family_id='+encodeURIComponent($("#family_id").val());
    }
    console.log(url);
    $("#helpscreen").html("<i>Loading content...</i>url="+url).dialog({ title: 'Creating List' }).dialog("open");
    $.ajax({
        url: url,
    }).done(function( json ) {
        if (json.error) {
            alert(json.error);
        } else if (json.success) {
            console.log(json);
            console.log(json.success);
            console.log(json.error);
            console.log(json.foo);
            $("#helpscreen").dialog("close");
            $("#schedule-div").html(json.foo);
            //$("#item_container").html(json.item_list);
            $("#schedule-div").dialog("open");
        }
    });
}
function familyChanged()
{
    if (typeof familyChanged.family_id == 'undefined' || familyChanged.family_id != $("#family_id").val()) {
        familyChanged.family_id = $("#family_id").val();
        redrawTable();
    }
    return true;
}
// Note that any change here needs to be reflected in the initial draw of the table in PHP
function redrawTable()
{
    var familyID = $("#family_id").val();
    var family_name = $("#family_id option:selected").text();
    console.log("redrawTable(): Entering familyID="+familyID+" name="+family_name);
    for (var i=0; i<slots.length; i++) {
        //console.log("redrawTable(): i="+i+", name="+slots[i].family_name+", id="+slots[i].id);
        changeSlot(i);
    }
}
// Note that any change here needs to be reflected in the initial draw of the table in PHP
function unsignupButtonText(id, name)
{
    return "<button class='ui-state-highlight' onclick='unsignup("+id+")'>"+name+"</button>";
}
// Note that any change here needs to be reflected in the initial draw of the table in PHP
function signupButtonText(id)
{
    return "<button onclick='signup("+id+")'>Sign&nbsp;Up</button>";
}
function unsignup(slot_id)
{
    var familyID = $("#family_id").val();
    if (!familyID) {
        alert('You must choose your name first');
        $("#family_id").focus();
        return;
    }
    if (confirm('Press OK to unregister yourself for this timeslot.')) {
        changeFamily(slot_id, '!NULL!');
    }
}
function signup(slot_id)
{
    //var family_id = $("#family_id").html();
    //var family_id = <?= $familyID ?>;
    //if (!family_id) {
        //alert('You must enter your name first');
        //$("#client_name").focus();
        //return;
    //}
    var familyID = $("#family_id").val();
    changeFamily(slot_id, familyID);
}
function changeFamily(slot_id, family_id)
{
    console.log(slot_id);
    madeChanges = true;
    <?php echo "var school_id = $schoolID;\n"; ?>
    var familyID = $("#family_id").val();
    console.log("ajax_signup.php?slot_id="+encodeURIComponent(slot_id)+"&family_id="+encodeURIComponent(family_id)+"&school_id="+encodeURIComponent(school_id))
    jQuery.ajax("ajax_signup.php?slot_id="+encodeURIComponent(slot_id)+"&family_id="+encodeURIComponent(family_id)+"&school_id="+encodeURIComponent(school_id))
        .done(function(json) {
            console.log("success");
            console.log(json);
            //console.log("slotid="+slot_id);
            //console.log("family_id="+json.family_id);
            if (json.success) {
                if (json.conflicts > 0) {
                    var msg = 'NOTE: You are already signed up elsewhere during that time! ('+json.conflicts+' time';
                    if (json.conflicts > 1)
                        msg += 's';
                    msg += ' in addition to this slot)';
                    alert(msg);
                }
                if (json.family_id == '!NULL!') {
                    json.family_id = null;
                    json.family_name = null;
                }
                changeSlot(-1, json.id, json.family_id, json.name);
            } else {
                console.log('error');
                console.log(json);
                alert(json.error);
            }
        });
}
// If idx is negative then we find the appropriate idx in slots
// If idx is non-neg then other args are optional because we can get them from slots
function changeSlot(idx, slot_id, family_id, family_name)
{
    var familyID = $("#family_id").val();
    console.log('changeSlot('+idx+','+slot_id+','+family_id+','+family_name+'): familyID='+familyID);
    if (idx < 0) {
        var found = false;
        for (i = 0; i < slots.length; i++) {
            if (slots[i].id == slot_id) {
                found = true;
                idx = i;
                break;
            }
        }
        if (!found) { return false; }
        console.log('changeSlot(): found: idx='+idx);
    }
    if (typeof slot_id == 'undefined') { slot_id = slots[idx].id; }
    if (typeof family_id == 'undefined') { 
        family_id = slots[idx].family_id;
        family_name = slots[idx].family_name; 
    } else if (family_id != slots[idx].family_id) { 
        slots[idx].family_id = family_id; 
        slots[idx].family_name = family_name; 
    }
    console.log('changeSlot(): slot_id='+slot_id+', family_id='+family_id+', family_name='+family_name);

    if (slots[idx].family_id) {
        console.log('changeSlot(): has slots['+idx+'].family_id='+slots[idx].family_id);
        if (slots[idx].family_id == familyID) {
            html = unsignupButtonText(slots[idx].id, family_name);
        } else {
            html = slots[idx].family_name;
        }
    } else {
        console.log('changeSlot(): no slots['+idx+'].family_id');
        html = signupButtonText(slots[idx].id);
    }
    //console.log("changeSlot(): html="+html);
    $("#detail_"+slots[idx].id).html(html);
}
// This function provides a little optimization in case someone leaves the page open
// for a long time - it will check less and less often, lowering load on the server
//   (comments assume this function is being called on an interval of 15 seconds)
function timedCheckForChanges(seconds)
{
    arguments.callee.count = ++arguments.callee.count || 1;
    if (madeChanges) {
        arguments.callee.count = 1;
        madeChanges = false;
    }

    var time = new Date();
    //console.log( ("0" + time.getHours()).slice(-2)   + ":" + ("0" + time.getMinutes()).slice(-2) + ":" + ("0" + time.getSeconds()).slice(-2)+ ' - timedCheckForChanges(): Entering');
    if (arguments.callee.count > 720) { // after 3 hours
        if (arguments.callee.count % 120 != 0) // check only every 30 mins
            return;
    } else if (arguments.callee.count > 480) { // after 2 hrs
        if (arguments.callee.count % 60 != 0) // check only every 15 mins
            return;
    } else if (arguments.callee.count > 240) { // after 60 mins
        if (arguments.callee.count % 20 != 0) // check only every 5 mins
            return;
    } else if (arguments.callee.count > 40) { // after 10 mins
        if (arguments.callee.count % 4 != 0) // check only every 1 mins
            return;
    }
    checkForChanges(seconds);
}
function checkForChanges(seconds)
{
    //console.log("checkForChanges(): Entering");
    <?php echo "var school_id = $schoolID;\n"; ?>
    jQuery.ajax("ajax_check4changes.php?school_id="+encodeURIComponent(school_id)+"&seconds="+encodeURIComponent(seconds))
        .done(function(json) {
            console.log("check4changes(): success="+json.success);
            //console.log(json);
            for (var row in json) {
                //console.log('row:');
                //console.log(row);
                if (json[row].id) {
                    //console.log("check4changes(): id="+json[row].id+", name="+json[row].family_name);
                    var found=false;
                    var changes=0;
                    for (var i=0; i<slots.length && !found; i++) {
                        if (json[row].id == slots[i].id) {
                            found=true; // don't loop anymore - small optimization
                            var newid=(json[row].family_id == null)?'':json[row].family_id;
                            if (newid != slots[i].family_id) {
                                //console.log("check4changes(): id="+json[row].id+", old name="+slots[i].family_name);
                                slots[i].family_name=(json[row].family_name == 'null')?'':json[row].family_name;
                                slots[i].family_id=(json[row].family_id == 'null')?'0':json[row].family_id;
                                //console.log("check4changes(): id="+json[row].id+", new name="+slots[i].family_name);
                                changes++;
                            }
                        }
                    }
                }
            }
            if (changes > 0)
                redrawTable();
        });
}
$(document).ready(function () {
//    $("#client_name").autocomplete({
//        source: "ajax_client.php",
//        change: function (event, ui) { clientChanged(); },
//        focus: function (event, ui) { 
//            //console.log(ui);
//            $("#client_name").val(ui.item.value); 
//            clientChanged(); 
//        },
//    });
    // check for changes within last 20 seconds every 15 seconds
    setInterval(function () {timedCheckForChanges(20);}, 15000);
    $( "#schedule-div" ).dialog({ 
         autoOpen: false
        ,modal: true
        ,width: 'auto'
        ,maxHeight: $(document).height() * 0.8
        ,maxWidth: $(document).width() * 0.8
        ,buttons: {
            Cancel: {
                text: "Cancel",
                click: function() {
                    $(this).dialog("close");
                }
            },
            Print: {
                text: "Print",
                click: function() {
                    $(this).printArea({mode: 'popup', popClose: 1, });
                }
            },
        }
    });
    $(".link2button").button().css({width: '200px'});
});
</script>
</head>
<body>
<?php

#    if (!$familyID) {
#        echo "ERROR: Unable to find departments with no familyID. Maybe you're a teacher?<br />\n";
#        exit ;
#    }
$sql = "SELECT depts.id AS dept_id, depts.name AS dept_name 
        FROM ".dbTable('depts')." depts 
            INNER JOIN ".dbTable('courses')." courses ON (courses.dept_id = depts.id)
            INNER JOIN ".dbTable('courses_students')." courses_students ON (courses.id = courses_students.course_id)
            INNER JOIN ".dbTable('students')." students ON (students.id = courses_students.student_id)
        WHERE students.family_id = $familyID
          AND depts.school_id = $schoolID
          AND (depts.opens IS NULL OR depts.opens <= NOW())
          AND (depts.closes IS NULL OR depts.closes >= NOW())
        UNION
        SELECT depts.id AS dept_id, depts.name AS dept_name 
        FROM ".dbTable('depts')." depts 
            INNER JOIN ".dbTable('courses')." courses ON (courses.dept_id = depts.id)
            INNER JOIN ".dbTable('users')." teachers ON (courses.teacher_id = teachers.id AND teachers.is_teacher)
        WHERE teachers.id = $userID 
          AND depts.school_id = $schoolID
          AND (depts.opens IS NULL OR depts.opens <= NOW())
          AND (depts.closes IS NULL OR depts.closes >= NOW()) ";
if (isAdmin($userID)) {
    $sql .=
       "UNION
        SELECT depts.id AS dept_id, depts.name AS dept_name 
        FROM ".dbTable('depts')." depts 
            INNER JOIN ".dbTable('courses')." courses ON (courses.dept_id = depts.id)
            INNER JOIN ".dbTable('users')." teachers ON (courses.teacher_id = teachers.id AND teachers.is_teacher)
        WHERE depts.school_id = $schoolID ";
}
$sql .= "GROUP BY dept_id, dept_name";
#echo "DEBUG: sql=$sql<br />\n";
$results = dbQuery($sql);
$rows = dbFetchAll($results);
#echo "DEBUG: rows=<pre>".print_r($rows,true)."</pre><br />\n";
$dept_cnt = sizeof($rows);
if ($dept_cnt == 0) {
    echo "Sorry - it doesn't look like you have any classes associated with you.<br />\n";
    exit;
} 
echo "<a href='".htmlentities($_SERVER['PHP_SELF'])."?logout=1' class='link2button' style='position:absolute; right:0; top:0'>Logout</a>\n";
if ($dept_cnt == 1 || !@$_REQUEST['dept_id']) {
    $deptID = $_REQUEST['dept_id'] = $rows[0]['dept_id'];
} else
    $deptID = $_REQUEST['dept_id'];
if ($dept_cnt > 1) {
    $dept_plural = ($dept_cnt > 1 ? 's' : '');
    echo "Hello, $m[FirstName]!  It looks like you have classes in $dept_cnt Department$dept_plural <br />\n";

    foreach ($rows as $row) {
        #echo "DEBUG: row=<pre>".print_r($row,true)."</pre><br />\n";
        echo "<a href='".htmlentities($_SERVER['PHP_SELF'])."?view=$curView&dept_id=$row[dept_id]' class='link2button";
        if ($row['dept_id'] == @$deptID) echo " ui-state-highlight";
        echo "'>$row[dept_name]</a>\n";
    }

    if (!@$_REQUEST['dept_id']) { // this should never happen as it defaults to the first dept_id in $rows
        echo "<br />Please choose a department above.<br />\n";
        exit;
    } 
}

$unavailable_array = array(array('id'=>-1, 'name'=>'Unavailable'));
if ($curView == 'FAMILY' && $familyID) {
    $sql = "SELECT DISTINCT families.id AS id, families.name AS name 
            FROM ".dbTable('depts')." depts 
                INNER JOIN ".dbTable('courses')." courses ON (courses.dept_id = depts.id)
                INNER JOIN ".dbTable('courses_students')." courses_students ON (courses.id = courses_students.course_id)
                INNER JOIN ".dbTable('students')." students ON (students.id = courses_students.student_id)
                INNER JOIN ".dbTable('families')." families ON (students.family_id = families.id)
            WHERE families.id = $familyID
              AND depts.school_id = $schoolID
              AND depts.id = $deptID
              AND (depts.opens IS NULL OR depts.opens <= NOW())
              AND (depts.closes IS NULL OR depts.closes >= NOW())";
    $results = dbQuery($sql);
    $families = dbFetchAll($results); // will be either null (if not found) or a single id/name record from families
    $familySource = 'FAMILY';
}
if ($curView == 'TEACHER') {
    $sql = "SELECT DISTINCT families.id AS id, families.name AS name 
            FROM ".dbTable('depts')." depts 
                INNER JOIN ".dbTable('courses')." courses ON (courses.dept_id = depts.id)
                INNER JOIN ".dbTable('users')." teachers ON (courses.teacher_id = teachers.id AND is_teacher)
                INNER JOIN ".dbTable('courses_students')." courses_students ON (courses.id = courses_students.course_id)
                INNER JOIN ".dbTable('students')." students ON (students.id = courses_students.student_id)
                INNER JOIN ".dbTable('families')." families ON (students.family_id = families.id)
            WHERE teachers.id = $userID 
              AND depts.school_id = $schoolID
              AND depts.id = $deptID
              AND (depts.opens IS NULL OR depts.opens <= NOW())
              AND (depts.closes IS NULL OR depts.closes >= NOW()) 
            ORDER BY families.name, families.id";
    #echo "DEBUG: sql=$sql<br />\n";
    $results = dbQuery($sql);
    $families = array_merge($unavailable_array, dbFetchAll($results));
    $familySource = 'TEACHER';
}
if (isAdmin($userID) && $curView == 'ADMIN') {
    # Technically I don't need the depts table in this query, but it maintains consistency from above...
    $sql = "SELECT DISTINCT families.id AS id, families.name AS name 
            FROM ".dbTable('depts')." depts 
                INNER JOIN ".dbTable('courses')." courses ON (courses.dept_id = depts.id)
                INNER JOIN ".dbTable('courses_students')." courses_students ON (courses.id = courses_students.course_id)
                INNER JOIN ".dbTable('students')." students ON (students.id = courses_students.student_id)
                INNER JOIN ".dbTable('families')." families ON (students.family_id = families.id)
            WHERE depts.school_id = $schoolID
              AND depts.id = $deptID
            ORDER BY families.name, families.id";
    #echo "DEBUG: sql=$sql<br />\n";
    $results = dbQuery($sql);
    $families = array_merge($unavailable_array, dbFetchAll($results));
    $familySource = 'ADMIN';
}
if (!$families) {
    echo "ERROR: Something is wrong in the configuration of your system. Your login has no associated families. Aborting.<br />\n";
    exit;
}

#echo "DEBUG: families = <pre>".print_r($families,true)."</pre><br /><br />\n";

################################################
#
# Display the view button (if applicable)
#
################################################
$altView = '';
if ($curView != 'ADMIN' && isAdmin($userID))
    $altView = 'Admin';
elseif ($curView == 'ADMIN') {
    if ($familyID) {
        $altView = 'Family';
    } else {
        $altView = 'Teacher';
    }
}
if ($altView)
    echo "<br /><a href='".htmlentities($_SERVER['PHP_SELF'])."?dept_id=$deptID&view=".strtoupper($altView)."' class='link2button'>Change to $altView View</a>\n";

################################################
#
# Display the family name (list) option
#
################################################
$selectedFamilyID = $firstFamilyID = 0;
if ($curView == 'FAMILY') $invisible = 'display:none; ';
else $invisible = '';
echo "<br />\n<select id='family_id' name='family_id' onchange='familyChanged()' style='$invisible'>\n";
    #echo "DEBUG: families=<pre>".print_r($families,true)."</pre><br />\n";
foreach ($families as $family) {
    #echo "DEBUG: family=<pre>".print_r($family,true)."</pre><br />\n";
    if (!$firstFamilyID) $firstFamilyID = $family['id'];
    if (@$_REQUEST['family_id'] && $_REQUEST['family_id'] == $family['id']) {
        $selected='selected="selected"';
        $selectedFamilyID = $family['id'];
    } else
        $selected='';
    echo "<option $selected value='$family[id]'>$family[name]</option>\n";
}
echo "</select>\n<br />\n";
echo '<button onclick="showSchedule()" class="link2button">Show Schedule</button>'."\n";
if (!$selectedFamilyID)
    $selectedFamilyID = $firstFamilyID;

/*
$familyID = '129281';
$familyClasses = $client->fetch("/User/$familyID/Classes");
echo "DEBUG: familyClasses($familyID)=<pre>".print_r($familyClasses,true)."</pre><br />\n";
ob_flush();

$familyID = '129281';
$familyClasses = $client->fetch("/Student/$familyID/Classes");
echo "DEBUG: familyClasses($familyID-student)=<pre>".print_r($familyClasses,true)."</pre><br />\n";
ob_flush();

$jonID = '390793';
$jonClasses = $client->fetch("/User/$jonID/Classes");
echo "DEBUG: jonClasses($jonID)=<pre>".print_r($jonClasses,true)."</pre><br />\n";
ob_flush();

$jonID = '390793';
$jonClasses = $client->fetch("/Student/$jonID/Classes");
echo "DEBUG: jonClasses($jonID-student)=<pre>".print_r($jonClasses,true)."</pre><br />\n";
ob_flush();

$peterID = '115798'; // 115798 is Peter, 390793 is Jonny, 129281 is Bowers family
$peterClasses = $client->fetch("/User/$peterID/Classes");
echo "DEBUG: peterClasses($peterID)=<pre>".print_r($peterClasses,true)."</pre><br />\n";
ob_flush();

#$peterID = '115798'; // 115798 is Peter, 390793 is Jonny, 129281 is Bowers family
#$peterClasses = $client->fetch("/Student/$peterID/Classes");
#echo "DEBUG: peterClasses($peterID-student)=<pre>".print_r($peterClasses,true)."</pre><br />\n";
#ob_flush();

$courseID = '174299'; // underwater basketweaving
$courseID = '240550'; // 7 Bible - should be nonactive
$courseID = '144869'; // 5 ICT - Jonny part
$myClass = $client->fetch("/School/$schoolID/Classes/$courseID");
$c = $myClass['result'];
echo "DEBUG: c=<pre>".print_r($c,true)."</pre><br />\n";
ob_flush();
 */

################################################
#
# Query/Display the actual table of time slots
#
################################################
$sql = "SELECT slots.id, slots.start_time as real_start_time, '' AS comment, 
             DATE_FORMAT(slots.start_time, '$date_fmt') as start_date,  
             DATE_FORMAT(slots.start_time, '$time_fmt') as start_time,  
             DATE_FORMAT(slots.end_time, '$time_fmt') as end_time,  
             teacher_id, teachers.display_name, slots.family_id AS family_id, 
             IF(slots.family_id = -1, 'Unavailable', families.name) as name
        FROM ".dbTable('slots')." slots
            LEFT JOIN ".dbTable('families')." families ON families.id = slots.family_id 
            JOIN ".dbTable('users')." teachers ON slots.teacher_id = teachers.id AND teachers.is_teacher = 1 ";
$sql .="WHERE slots.school_id = $schoolID
            AND slots.dept_id = $_REQUEST[dept_id] ";
if ($curView == 'TEACHER')
    $sql .="AND teachers.id = $userID ";
elseif ($curView == 'FAMILY')
    $sql .= " AND slots.teacher_id IN 
    (SELECT teacher_id 
     FROM ".dbTable('courses')." courses 
        JOIN ".dbTable('courses_students')." courses_students ON (courses.id = courses_students.course_id) 
        JOIN ".dbTable('students')." students ON (courses_students.student_id = students.id) 
    WHERE students.family_id = $familyID) ";
$sql .= " ORDER BY slots.start_time, teachers.lname, teachers.fname";
#echo "DEBUG: sql=<pre>$sql</pre><br />\n";
$result = dbQuery($sql);
$last_date = $last_time = $real_last_time = $first_time = '';
$cols = 2; // left column and right column is time
$teacher_row = '<tr><th>&nbsp;</th>';
$out = '<table class="ui-widget-content" style="margin:auto; " >TEACHER_ROW';
$jsarray = "\n".'var slots = [';
$reccount = 0;
while ($row = dbFetch($result)) {
    $reccount++;
    $jsarray .= "{ id:".$row['id'].", family_id: ".($row['family_id']?:0).", family_name:'".$row['name']."'},\n";
    #echo "DEBUG: row=<pre>".print_r($row,true)."</pre>\n";
    if ($real_last_time != $row['real_start_time']) {
        if ($last_time) $out .= "<td>$last_time</td></tr>";
        if ($last_date != $row['start_date']) {
            $out .= "<tr class='ui-widget-header'><th colspan='\$\$ColumnCount'>$row[start_date]</th></tr>";
            $last_date = $row['start_date'];
        }
        $out .= "<tr><td>$row[start_time]</td>";
        $real_last_time = $row['real_start_time'];
        $last_time = $row['start_time'];
    }
    if (!$first_time) $first_time = $row['real_start_time'];
    if ($first_time == $row['real_start_time']) {
        if ($curView == 'FAMILY')
            $sql = "SELECT courses.name, CONCAT(students.fname, ' ', students.lname) AS display_name
                    FROM ".dbTable('courses')." courses 
                      JOIN ".dbTable('courses_students')." courses_students ON (courses.id = courses_students.course_id)
                      JOIN ".dbTable('students')." students ON (courses_students.student_id = students.id)
                    WHERE dept_id = $deptID 
                      AND teacher_id = $row[teacher_id] 
                      AND students.family_id = $familyID
                      ORDER BY name";
        else # either ADMIN or TEACHER
            $sql = "SELECT courses.name, '' AS display_name
                    FROM ".dbTable('courses')." courses 
                    WHERE school_id = $schoolID
                      AND dept_id = $deptID 
                      AND teacher_id = $row[teacher_id] 
                      ORDER BY name";
        $courseResults = dbQuery($sql);
        $courseList = $sep = '';
        while ($courseRow = dbFetch($courseResults)) {
            $courseList .= "$sep$courseRow[name] ($courseRow[display_name])";
            $sep = "\n";
        }
        $teacher_row .= "<th><span title='$courseList'>$row[display_name]</span></th>";
        $cols++;
    }
    $out .= "<td id='detail_$row[id]' data-family-id='$row[family_id]' align='center'>";
    if ($row['family_id'])
        if ($row['family_id'] == $selectedFamilyID)
            $out .= "<button class='ui-state-highlight' onclick='unsignup($row[id])'>$row[name]</button>";
        else
            $out .= "$row[name]";
    else
        $out .= "<button onclick='signup($row[id])'>Sign&nbsp;Up</button>";
    $out .= "</td>\n";
}
if ($reccount) {
    $out .= "<td>$last_time</td></tr>TEACHER_ROW</table>";
    $teacher_row .= "<th>&nbsp;</th></tr>";
    $out = str_replace(array('TEACHER_ROW', '$$ColumnCount'), array($teacher_row, $cols), $out);
    echo $out;
    $jsarray .= "];";
    echo "\n<script type='text/javascript'>\n$jsarray\n</script>\n";
} else {
    echo "You are not authorized to change any time slots.<br />\n";
}
?>
<div id="helpscreen" style="display:none">
    <i>Please wait. Loading content.</i>
</div>
<div id="schedule-div" style="display:none">
    <div id="schedule-div-errors" style="color:red;"></div>
</div>
</body>
</html>
